package com.pfzy.lib.net.cookie;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import okhttp3.Cookie;

/**
 * 可序列化OkHttp Cookie
 */
public class SerializableOkHttpCookies implements Serializable {
    private transient Cookie clientCookies;
    private final transient Cookie cookies;

    public SerializableOkHttpCookies(Cookie cookies) {
        this.cookies = cookies;
    }

    public Cookie getCookies() {
        Cookie bestCookies = this.cookies;
        if (this.clientCookies != null) {
            Cookie bestCookies2 = this.clientCookies;
            return bestCookies2;
        }
        return bestCookies;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(this.cookies.name());
        out.writeObject(this.cookies.value());
        out.writeLong(this.cookies.expiresAt());
        out.writeObject(this.cookies.domain());
        out.writeObject(this.cookies.path());
        out.writeBoolean(this.cookies.secure());
        out.writeBoolean(this.cookies.httpOnly());
        out.writeBoolean(this.cookies.hostOnly());
        out.writeBoolean(this.cookies.persistent());
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        String name = (String) in.readObject();
        String value = (String) in.readObject();
        long expiresAt = in.readLong();
        String domain = (String) in.readObject();
        String path = (String) in.readObject();
        boolean secure = in.readBoolean();
        boolean httpOnly = in.readBoolean();
        boolean hostOnly = in.readBoolean();
        in.readBoolean();
        Cookie.Builder builder = new Cookie.Builder().name(name).value(value).expiresAt(expiresAt);
        Cookie.Builder builder2 = (hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain)).path(path);
        if (secure) {
            builder2 = builder2.secure();
        }
        if (httpOnly) {
            builder2 = builder2.httpOnly();
        }
        this.clientCookies = builder2.build();
    }
}
